package com.rave.pricechangeanimationdemo;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.LinearInterpolator;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * 作者：tianrenzheng on 2020/3/10 14:35
 * 邮箱：317642600@qq.com
 */
public class PriceAnimationTextView extends AppCompatTextView {
    private static final String TAG = PriceAnimationTextView.class.getSimpleName();
    private static final long ANIMATION_DEFAULT_DURATION = 200L;
    private static final int PRICE_DEFAULT_SCALE = 2;
    private ValueAnimator priceChangeAnimation;
    private String startPriceText;
    private String deltaPriceText;

    public PriceAnimationTextView(Context context) {
        this(context, null);
    }

    public PriceAnimationTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PriceAnimationTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        priceChangeAnimation = ValueAnimator.ofInt(0,100);
        priceChangeAnimation.setDuration(ANIMATION_DEFAULT_DURATION);
        priceChangeAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.d(TAG, "Animation Value:" + animation.getAnimatedValue() + ", Animation Fraction:" + animation.getAnimatedFraction());
                String tempPrice = BigDecimalUtils.add(startPriceText, BigDecimalUtils.mul(deltaPriceText, animation.getAnimatedFraction() + ""));
                setText(BigDecimalUtils.setScaleTrailingZero(tempPrice, PRICE_DEFAULT_SCALE));
            }
        });
    }

    public void setAnimationText(String newText) {
        if (BigDecimalUtils.isNumeric(newText) && BigDecimalUtils.isNumeric(this.getText().toString())) {
            startPriceText = this.getText().toString();
            deltaPriceText = BigDecimalUtils.sub(newText, startPriceText);
            priceChangeAnimation.cancel();
            priceChangeAnimation.setInterpolator(new LinearInterpolator());
            priceChangeAnimation.start();
        } else {
            setText(newText);
        }
    }
}
